import {Component, ElementRef, OnDestroy, OnInit, Renderer, ViewChild, ViewEncapsulation} from '@angular/core';
import {Router} from '@angular/router';

import {SeedInfiniteScroll} from 'app/shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component';
import {ImageServeService} from 'app/shared/service/image/image-serve.service';
import {ToolsService} from 'app/shared/service/tools/tools.service';

import {Subject} from "rxjs/Subject";
import {MixService} from "./mix.service";
import {ColumnContentVO} from "../../interface/column/column.models";
import {AppPlayTurn} from "@interface/index";
// import {ColumnContentVO} from "@interface/column/column.models";
// import {AppPlayTurn} from "@interface/interface/interface.model";


declare var window;

@Component({
  selector: 'mix',
  templateUrl: './mix.component.html',
  styleUrls: ['./mix.component.scss'],
  encapsulation: ViewEncapsulation.None,
})

export class MixComponent implements OnInit, OnDestroy {
  public goodsModules: Array<ColumnContentVO> = [];
  public bannerObj: AppPlayTurn[];
  public recommendGoods: Array<any> = [];

  @ViewChild(SeedInfiniteScroll) infiniteScroll;
  @ViewChild('card') card: ElementRef;
  @ViewChild('container') container: ElementRef;

  public params = {
    page: 1,
    rows: 10
  };

  public dataStore = {
    goodsType: [], // 商品类别
    screenWidth: 0
  };
  public layoutStore = {
    common: {
      padding: 0.03, // percent
      border: 1, // px
    },
    columnType: {
      one: {
        itemWidth: 1,
        imgHeight: 0
      },
      oneHalf: {
        itemWidth: 0.27, // percent
        imgHeight: 0,
        scale: 1.89
      },
      two: {
        itemWidth: 0.485, // percent
        imgHeight: 0
      }
      , three: {
        itemWidth: 0.315, // percent
        imgHeight: 0
      },
      threeHalf: {
        itemWidth: 0.27, // percent
        imgHeight: 0
      }
      , four: {
        itemWidth: 0.23, // percent
        imgHeight: 0
      }
    }
  };

  public ngUnsubscribe: Subject<void> = new Subject<void>();

  constructor(
    private router: Router,
    public mixService: MixService,
    public toolsService: ToolsService,
    public tools: ToolsService,
    public imgService: ImageServeService,
    private ele: ElementRef,
    private renderer: Renderer
  ) {
  }

  /**
   * @description 获取轮播图
   * @author ouyqx-691
   * @date 2017-09-12
   */
  getSlider() {
    this.mixService.getSlider().takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0' && res.data) {
        this.bannerObj = res.data.list;
      }
    });
  };

  /**
   * @description 前往商品详情
   * @author ouyqx-691
   * @date 2017/11/24
   * @param news 单个轮播对象
   */
  goToBannerTarget(slide) {
    // 外链且存在外链url
    if (slide.linkType === 2 && slide.detailUrl) {
      if (slide.detailUrl.indexOf('topicId') === -1) {
        window.open(slide.detailUrl);
      } else {
        const topicId = slide.detailUrl.split('topicId=')[1];
        this.router.navigate(['/goods/topic', topicId]);
      }
    }

    if (slide.linkType === 1 && slide.resId) {
      window.open(slide.detailUrl);
      // resType (string, optional): 资源类型 （1：帖子 ，2： 视频 ，3：资讯 4：个人秀 ，5：赛事 ，6： 商品） ,
      // switch (slide.resType) {
      //   case 1:
      //     this.router.navigate(['/feed/detail', slide.resId]);
      //     break;
      //   case 2:
      //     this.router.navigate(['/video/detail', slide.resId]);
      //     break;
      //   case 3:
      //     this.router.navigate(['/news', slide.resId]);
      //     break;
      //   case 5:
      //     this.router.navigate(['/match/detail', slide.resId]);
      //     break;
      //   case 6:
      //     this.router.navigate(['/goods/detail',  slide.resId]);
      //     break;
      // }
    }
  }

  /**
   * @description 获取商品类型
   * @author ouyqx-691
   * @date 2017-11-16
   */
  getGoodsType() {
    this.mixService.getGoodsType().takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0' && res.data) {
        let goodsCategoryList = [];
        const allGoodsCategoryList = res.data.goodsCategoryList;

        if (allGoodsCategoryList.length <= 8) {
          this.dataStore.goodsType = allGoodsCategoryList;
        } else {
          goodsCategoryList = allGoodsCategoryList.slice(0, 7);
          const all = {
            serviceName: '全部',
            targetUrl: '/goods/nav',
            iconUrl: this.imgService.getIcon('icon_all.png')
          };
          goodsCategoryList.push(all);
          this.dataStore.goodsType = goodsCategoryList;
        }
      }
    });
  };

  /**
   * @description go to goods list page
   * @param nav :nav object
   */
  goToNavTarget(nav) {
    if (nav.targetUrl) { // 点击全部
      this.router.navigate(['/goods/nav']);
      return;
    }
    // 未配置链接
    if (!nav.serviceUrl) {
      return;
    }
    // linkType : string): 链接方式 （0： 专题导航 ，1：商品导航） ,
    if (nav.navType !== '0') { // 专题导航
      const topicId = nav.serviceUrl.split('topicId=')[1];
      if (topicId) {
        this.router.navigate(['/goods/topic/', topicId]);
      }
      return;
    } else { // 商品导航
      const goodsCategoryCode = nav.serviceUrl.split('goodsCategoryCode=')[1];
      if (goodsCategoryCode) {
        if (goodsCategoryCode.toLocaleLowerCase() === 'v18') {
          this.router.navigate(['/goods/p']);
          return;
        }
        this.router.navigate(['/goods/list/', goodsCategoryCode], {
          queryParams: {
            title: encodeURI(nav.serviceName)
          }
        });
      }
    }
  }


  /**
   * @description 获取推荐商品布局信息
   * @author ouyqx-691
   * @date 2017-09-11
   */
  getGoodsModule() {
    this.tools.showLoading();
    this.mixService.getGoodsModule().takeUntil(this.ngUnsubscribe).subscribe(res => {
      this.tools.hideLoading();
      if (res.result === '0') {
        const modules = res.data;
        let layoutType;
        for (let i = 0; i < modules.length; i++) {
          const list = modules[i].contentList;
          for (let j = 0; j < list.length; j++) {
            // 图片链接
            if (list[j].contentType === 0) {
              if (list[j].verticalDisplay === 0) {
                layoutType = 'fullPicture';
              } else if (list[j].verticalDisplay === 1) {
                layoutType = 'halfPicture';
              }
            } else if (list[j].contentType === 1) { // 商品
              if (list[j].verticalDisplay === 0) {
                layoutType = 'fullGoods';
              } else if (list[j].verticalDisplay === 1 || list[j].verticalDisplay === 3) {
                layoutType = 'halfGoods';
              }
            }
            // 一行多列
            if (list[j].verticalDisplay === 2) {
              layoutType = 'quarter';
            } else if (list[j].verticalDisplay === 3) {
              layoutType = 'third';
            }
            Object.assign(list[j], {
              layoutType: layoutType
            });
          }
        }
        this.goodsModules = modules;
      }
    });
  };

  /**
   * @description 获取推荐商品
   * @author ouyqx-691
   * @date 2017-09-11
   */
  getRecommendGoods() {
    this.mixService.getRecommendGoods(this.params).takeUntil(this.ngUnsubscribe).debounceTime(800).subscribe(res => {
      this.infiniteScroll.complete();
      if (res.result === '0' && res.data.list && res.data.list.length > 0) {
        const goods = res.data.list;
        this.params.page++;
        this.recommendGoods = this.recommendGoods.concat(goods);
        if (this.recommendGoods.length >= 200 || !res.data.hasNextPage) { // 限制只加载200条
          this.infiniteScroll.enable(false);
        }
      }
    });
  }

  /**
   * @description 处理是进入详情还是打开新窗口
   * @author ouyqx-691
   * @param goodsCode
   */
  handleDetail(goods) {
    if (goods.contentType === 1) {
      this.goToGoodsDetail(goods.nextStepUrl);
    } else {
      const link: string = goods.linkUrl;
      if (link) {
        window.open(link);
      }
    }
  }

  /**
   * @description 前往商品详情
   * @author ouyqx-691
   * @param goodsCode
   */
  goToGoodsDetail(url) {
    if (url) {
      this.router.navigate([url]);
      /**, {queryParams: {goodsCode: goodsCode}}*/
    }
  }

  /**@description 正方形图片适配
   * @author ouyqx-691
   * @date 2018/02/28
   */
  resetCardSize() {
    const screenWidth = window.screen.width;
    const layoutStore = this.layoutStore;
    const {padding, border} = layoutStore.common;
    const columnType = layoutStore.columnType;
    for (const type in columnType) {
      if (columnType.hasOwnProperty(type)) {
        // 处理普通布局
        columnType[type].imgHeight = (screenWidth - (screenWidth * padding * 2)) * columnType[type].itemWidth - border * 2;
        // 处理滑动布局
        if (type === 'oneHalf') {
          columnType[type].imgHeight = (screenWidth - screenWidth * padding * 2)
            * columnType[type].itemWidth * columnType[type].scale - border * 2;
        } else if (type === 'one') {
          columnType[type].imgHeight = (screenWidth - screenWidth * padding * 2)
            * columnType[type].itemWidth * 0.53 - border * 2;
        }
      }
    }
  }

  ngOnInit() {
    this.getSlider();
    this.getGoodsType();
    this.getGoodsModule();
    this.getRecommendGoods();

    this.resetCardSize();
    this.renderer.listen(window, 'resize', () => {
      this.resetCardSize();
    });
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  };
}
